package org.jeecg.modules.flowable.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.flowable.dto.FlowInstanceStartDTO;
import org.jeecg.modules.flowable.dto.FlowInstanceStopDTO;
import org.jeecg.modules.flowable.dto.FlowTaskOperationDTO;
import org.jeecg.modules.flowable.dto.FlowUserDTO;
import org.jeecg.modules.flowable.entity.FlowInstance;
import org.jeecg.modules.flowable.entity.TestDemo;
import org.jeecg.modules.flowable.mapper.TestDemoMapper;
import org.jeecg.modules.flowable.query.FlowTaskQuery;
import org.jeecg.modules.flowable.service.*;
import org.jeecg.modules.flowable.vo.FlowTaskVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("testDemoService")
public class TestDemoServiceImpl extends ServiceImpl<TestDemoMapper, TestDemo> implements TestDemoService {


    @Autowired
    FlowOperatorService flowOperatorService;


    @Autowired
    private FlowTaskService flowTaskService;

    @Autowired
    private FlowModelService flowModelService;

    @Autowired
    private FlowCategoryService flowCategoryService;

    @Autowired
    private FlowInstanceService flowInstanceService;



    final String BusinessKey = "TestDemo";

    public Result<Void> startProcessInstance(String dataId) {
        // 启动流程
        System.out.println(dataId + "\n");
        FlowInstanceStartDTO startDTO = new FlowInstanceStartDTO();

        FlowUserDTO loginUser = flowOperatorService.getLoginUser();

        // 设置流程发起用户
        startDTO.setUserId(loginUser.getId());
        startDTO.setUserName(loginUser.getUsername());
        // 设置发起表单信息 --> 模型定义的业务标识
        startDTO.setBusinessKey(BusinessKey);
        // 表单对应的唯一标识（用于区分不同的业务流程申请）
        startDTO.setBusinessDataId(dataId);
        // 表单参数（可以直接将DTO或ENTITY序列化为JSON）
        Map<String, Object> map = new HashMap<>();
        map.put("time", LocalDateTime.now());
        map.put("formid", "test1");
        startDTO.setBusinessData(JSONUtil.toJsonStr(map));
        System.out.println(startDTO.toString() + "\n");
        return flowInstanceService.start(startDTO);
    }

    public  Result<Void> stopProcessInstance(String dataId ) {
        // 停止流程
        FlowInstanceStopDTO  stopDTO = new FlowInstanceStopDTO();
        FlowInstance flowInstance = flowInstanceService.getInstanceByBusinessDataId(BusinessKey, dataId);
        if (flowInstance != null){
            stopDTO.setProcessInstanceId(flowInstance.getId());
            stopDTO.setMessage("正常停止流程");
            FlowUserDTO loginUser = flowOperatorService.getLoginUser();
            // 设置流程操作用户
            stopDTO.setUserId(loginUser.getId());
            stopDTO.setUserName(loginUser.getUsername());

            return flowInstanceService.stop(stopDTO);
        }

        return  Result.error("无法找到流程实例");

    }


    public  Result<Void> handleTask(String dataId, String message, String type) {
        FlowInstanceStopDTO  stopDTO = new FlowInstanceStopDTO();
        FlowInstance flowInstance = flowInstanceService.getInstanceByBusinessDataId(BusinessKey, dataId);
        if (flowInstance != null){
            FlowUserDTO loginUser = flowOperatorService.getLoginUser();
            FlowTaskQuery flowTaskQuery = new FlowTaskQuery();
            // 设置查询用户信息
            flowTaskQuery.setUserId(loginUser.getId());
            // 部门id
            flowTaskQuery.setDeptIds(Collections.singletonList(loginUser.getDepartIds()));
            List<String> roleIds = flowOperatorService.getRoleIdsByUsername(loginUser.getUsername());
            // 角色id
            flowTaskQuery.setRoleIds(roleIds);
            Result<Page<FlowTaskVO>> pageResult = flowTaskService.todoList(flowTaskQuery);
            FlowTaskVO flowTaskVO = pageResult.getResult().getRecords().get(0);


            //审核流程
            FlowTaskOperationDTO operationDTO = new FlowTaskOperationDTO();
            // 审批处置人
            operationDTO.setUserId(loginUser.getId());
            operationDTO.setUserName(loginUser.getUsername());
            // 审批节点
            operationDTO.setProcessInstanceId(flowTaskVO.getProcessInstanceId());
            operationDTO.setTaskId(flowTaskVO.getTaskId());
            // 审批信息
            operationDTO.setMessage(message);
            if (type == "complete"){
                flowTaskService.complete(operationDTO);
            }
            else  if (type == "veto"){
                flowTaskService.veto(operationDTO);
            }

            return  Result.ok("成功");
        }

        return  Result.error("无法找到流程实例");

    }


    @Override
    public IPage<TestDemo> myPage(Page<TestDemo> page, QueryWrapper<TestDemo> queryWrapper) {
        return this.baseMapper.myPage(page, queryWrapper);
    }

    @Override
    public boolean save(TestDemo testDemo) {
        /**新增数据，初始化流程关联信息**/
        testDemo.setId(IdUtil.fastSimpleUUID());
        this.startProcessInstance(testDemo.getId());
        return super.save(testDemo);
    }
    @Override
    public boolean removeById(Serializable id) {
        /**删除数据，移除流程关联信息**/
        stopProcessInstance(id.toString());

        return super.removeById(id);
    }

}
